<template>
  <div class="container">
    <el-form ref="addForm" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="学科名称" prop="subjectName">
        <el-input v-model="formData.subjectName" placeholder="请输入学科名称"></el-input>
      </el-form-item>
      <el-form-item label="是否显示">
        <el-switch
        v-model="value"
        active-color="#13ce66"
        inactive-color="#ff4949"
        :active-value= 1
        :inactive-value= 0
      >
      </el-switch>
      </el-form-item>

      <div class="btn">
        <el-form-item>
          <el-button @click="hCanel">取消</el-button>
          <el-button type="primary" @click="hSubmit">确定</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/subjects.js'
export default {
  props: {
    id: {
      type: Number,
      required: false
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      formData: {
        subjectName: ''
      },
      rules: {
        subjectName: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
      },
      value: 1
    }
  },
  created () {
    this.loadModify()
  },
  methods: {
    async doAdd () { // 新增请求
      if (this.isEdit === false) {
        await add({
          subjectName: this.formData.subjectName,
          isFrontDisplay: this.value
        })
        // console.log(res)
      }
    },
    async loadModify () { // 修改数据请求
      try {
        if (this.isEdit) {
          const res = await detail({ id: this.id })
          // console.log('fsdafasdf', res)
          this.formData = {
            subjectName: res.data.subjectName
          }
          this.value = res.data.isFrontDisplay
        }
      } catch (err) {
        console.log(err)
      }
    },
    async loadUpdate () { // 修改功能请求
      try {
        await update({
          id: this.id,
          subjectName: this.formData.subjectName,
          isFrontDisplay: this.value
        })
      } catch (err) {
        console.log(err)
      }
    },
    hSubmit () { // 确定按钮
      this.$refs.addForm.validate(
        valid => {
          if (valid) {
          // 做添加
            if (this.isEdit === false) {
              this.doAdd()
              this.$message.success('添加成功')
            } else {
              this.loadUpdate()
              this.$message.success('修改成功')
            }
            this.$emit('hBtn')
          }
        }
      )
    },
    hCanel () { // 取消按钮
      this.$emit('close')
      this.$message({
        type: 'info',
        message: '已取消'
      })
    }
  }
}
</script>

<style scoped>
.container {
  height: 300px;
}
.btn {
  float: right;
  margin-top: 150px;
}
</style>
